/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.handler;

import cn.ac.iie.di.wx.httpservice.HttpSender;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.mongoservice.MongoHelper;
import cn.ac.iie.di.wx.vo.PicUrlVo;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Administrator
 */
public class WxPictureUrl_new implements HandlerI {

    static Logger logger = Logger.getLogger(WxPictureUrl_new.class.getName());

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        boolean flag = false;
        try {
            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            //查库获取图片url，进行拼接后发送response,http连接资源释放问题需要注意,批量查询
            String _idurlStr = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
            logger.info(_idurlStr);
            HttpSender hs = new HttpSender();
            int count = 0;
            while (count <= 15) {
                if (RuntimeEnv.wxPictureUrlQueryLimit.get() < Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.WXPICQLIMIT))) {
                    RuntimeEnv.wxPictureUrlQueryLimit.incrementAndGet();
                    flag = true;
                    try {
                        JSONObject jsono = JSONObject.parseObject(_idurlStr);
                        String urlStr = jsono.getString("url");
                        String _id = jsono.getString("_id");
                        //判断是群发还是交互
                        String[] ss = _id.split("-");
                        String mwx = ss[1];
                        ArrayList<String> collection = new ArrayList<>();
                        collection.add(_id);
                        HashMap<String, Object> rnt = null;
                        String tableName = "";
                        String savePath = "";
                        if (mwx.equals("WX01")) {
                            //查群发   
                            tableName = (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWTABLENAME_GROUP);
                            savePath = "/home/jr/data/wx/mmdwd";
                        }
                        if (mwx.equals("WX02")) {
                            //查交互
                            tableName = (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWTABLENAME_INTERACTIVE);
                            savePath = "/home/jr/data/wx/mmdwd";
                        }

                        MongoHelper mongoHelper = null;
                        if (!tableName.equals("")) {
                            try {
                                String[] host = new String[1];
                                host[0] = (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWMONGOHOSTS);
                                mongoHelper = new MongoHelper(host,
                                        (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWDBNAME),
                                        tableName,
                                        (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWUSERNAME),
                                        (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWPASSWORD));
                                rnt = mongoHelper.findLfn("_id", collection);
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            } finally {
                                mongoHelper.conn.close();
                            }
                        }
                        String urlFromMongo = "";
                        urlFromMongo = (String) rnt.get(_id);
                        logger.info(urlFromMongo);
//                    logger.info(_id);
//                    logger.info(urlStr);
                        //先下载，后返回
//                        String urlresult = hs.sendStringByUrl(urlStr, (String) RuntimeEnv.getParam(RuntimeEnv.TXURL));//json的字符串
                        String urlresult = hs.sendStringByUrl("{\"cmd\":16,\"url\":\"" + urlStr + "\"}", (String) RuntimeEnv.getParam(RuntimeEnv.wxPicQueryUrl));//json的字符串
                        logger.info(urlresult);
//获取下载地址.可以直接下载，根据图片下载程序进行下载功能，有下载程序，下载完后才能返回mongoPicUrl,使用运行时参数类初始化一个下载的线程进行下载
                        if (!urlresult.equals("")) {
                            JSONObject urljSONObject = JSONObject.parseObject(urlresult);
                            String data = urljSONObject.getString("data");
                            if (!data.isEmpty()) {
                                JSONObject dldurljSONObject = JSONObject.parseObject(data);
                                String download_url = dldurljSONObject.getString("download_url");
//                            URL picDldUrl = new URL(download_url.replace("10.177.138.34", "10.238.3.12"));
                                InputStream responseIn = org.apache.http.client.fluent.Request.Get(download_url.replace("10.177.138.34", "10.238.3.12"))
                                        .execute().returnContent().asStream();

//                            logger.info(responseIn.available());
//                            while ((bytesReadIn = responseIn.read(bytesContent, 0, 1024 * 2)) > 0) {
//
//                            }
//                            logger.info(download_url);
                                //输出到文件让吉雨拉取，回传路径给吉雨和计算所，给计算所传路径的用setheader的方式，给吉雨的传消息队列
                                if (rnt.isEmpty()) {
                                    logger.error("can not find the url " + _id);
                                }
//                            logger.info(responseIn.available());                            //回传计算所的头部
                                if (urlFromMongo != null) {
                                    response.addHeader("url", urlFromMongo);
                                }
                                //写入本地文件
                                OutputStream outputStream = null;
                                BufferedOutputStream fileOut = null;
//                            logger.info(urlFromMongo);
                                try {
                                    if (urlFromMongo != null) {

                                        String abPath = savePath + urlFromMongo;
                                        String[] ap = abPath.split("/");
                                        String[] sss = abPath.split(ap[ap.length - 1]);
//                                logger.info("path" + sss[0] + "\t ss length" + sss.length);//路径
                                        //创建目录

                                        File f = new File(sss[0]);
//                                logger.info(f.exists());
                                        if (!f.exists() || !f.isDirectory()) {
                                            f.mkdirs();
                                        }
                                        String isExist = "0";
                                        File file = new File(abPath);
                                        if (!file.exists()) {
                                            try {
                                                file.createNewFile();

                                            } catch (IOException ex) {
                                                logger.error(ex.getMessage(), ex);
                                            }
                                        } else {
                                            isExist = "1";
                                        }
                                        outputStream = new FileOutputStream(file);
                                        fileOut = new BufferedOutputStream(outputStream);
                                        while ((bytesReadIn = responseIn.read(bytesContent, 0, 1024 * 2)) > 0) {
                                            bos.write(bytesContent, 0, bytesReadIn);
                                            fileOut.write(bytesContent, 0, bytesReadIn);
                                        }

                                        RuntimeEnv.picUrlBlockingQueue.add(new PicUrlVo(abPath.split("wxdata/")[1], isExist));
//                                logger.info(abPath);
                                        bos.flush();
                                        fileOut.flush();
                                        outputStream.close();
//                                responseIn.close(); //这个不能关闭
                                        fileOut.close();
                                        bos.close();
                                        f = null;
                                        file = null;
                                    } else {
                                        //查不到urlFromMongo
                                        logger.info("mongo查不到该id");
                                        while ((bytesReadIn = responseIn.read(bytesContent, 0, 1024 * 2)) > 0) {
                                            bos.write(bytesContent, 0, bytesReadIn);
                                        }
                                        bos.flush();
                                        bos.close();
                                    }

                                } catch (FileNotFoundException ex) {
                                    logger.error(ex.getMessage(), ex);
                                } finally {

                                }

                            }
                        } else {
                            logger.info("访问超时");
                            InputStream inputStream = new ByteArrayInputStream("腾讯图片接口调用失败".getBytes("UTF-8"));
                            while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                                bos.write(bytesContent, 0, bytesReadIn);
                            }
                            bos.flush();
                            bos.close();

                        }

                        //批量的话创建进程池,picurlkey为列名，urlresult为键名，键对应的值还为从tx获取
                        //获取图片流的方法未定
//                    mongoHelper.add("picurlkey", urlresult, f);
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                    RuntimeEnv.wxPictureUrlQueryCount.incrementAndGet();
                    break;
                }
                if (count >= 15) {
                    logger.info("访问量超限");
                    InputStream inputStream = new ByteArrayInputStream("腾讯图片接口调用失败".getBytes("UTF-8"));
                    while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                        bos.write(bytesContent, 0, bytesReadIn);
                    }
                    bos.flush();
                    bos.close();
                    break;
                }
                ++count;
                Thread.sleep(100);
            }
            //释放连接
//            Thread.sleep(1000);

        } catch (Exception e) {
            logger.error("Filedownload send out error\n" + e.getMessage(), e);

        } finally {
            if (flag) {
                RuntimeEnv.wxPictureUrlQueryLimit.decrementAndGet();
            }
        }
    }

    @Override
    public void init() throws Exception {
//        logger.info("init WxPictureUrl");
    }

    public static void main(String[] args) {
        String abPath = "/home/jr/data/wx/mmdwd/wxdata/wx_mass_pic/20170301/00476/42d93cd236de0e7942ed47ce8042c746.jpg";
        String[] ap = abPath.split("wxdata/");
//        String[] sss = abPath.split(ap[ap.length - 7]);
        logger.info(ap[1]);
    }
}
